/*
 * Copyright (C) 2020 Jimmy Hogoboom
 *
 * This file is part of Limitlist.
 *
 * Limitlist is free software: you can redistribute it and/or modify
 * it under the terms of the Affero GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Limitlist is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Affero GNU General Public License for more details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * along with Limitlist.  If not, see <https://www.gnu.org/licenses/>.
 */

// SPDX-License-Identifier: AGPL-3.0-or-later

import React, { useState } from 'react';
import { ProductListItemInput } from 'components/ProductListItem/types';
import { calculateTotal } from 'utils';
import './ProductList.scss';
import ProductListSortableContainer from './ProductListSortableContainer';
import { SortEndHandler, SortStartHandler } from 'react-sortable-hoc';
import { IProductListManagedComponentProps } from 'components/ProductListManager';
import { IProductListItem } from 'core/ProductListItem';

const mapItemToInput = (item: IProductListItem) => ({
  id: item.id,
  name: item.name,
  quantity: item.quantity?.toString(),
  price: item.price?.toFixed(2),
}) as ProductListItemInput;

const mapInputToItem = (input: ProductListItemInput) => ({
  id: input.id,
  name: input.name,
  quantity: input.quantity ? Number(input.quantity) : null,
  price: input.price ? Number(input.price) : null,
}) as IProductListItem;

const ProductList: React.FC<IProductListManagedComponentProps> = (props) => {
  const [isSorting, setIsSorting] = useState<boolean>(false);

  const onSortStart: SortStartHandler = () => {
    setIsSorting(true);
  };

  const onSortEnd: SortEndHandler = ({ oldIndex, newIndex }) => {
    props.moveItem!(oldIndex, newIndex);

    setIsSorting(false);
  };

  const itemList = props.items?.map(mapItemToInput) || [];

  const grandTotal = itemList
    ? itemList
      .map(i => Number(calculateTotal(i.price, i.quantity)))
      .reduce((a, b) => {
        return a + b;
      }, 0)
      .toFixed(2)
    : 0;

  const handleChange = (item: ProductListItemInput) => {
    props.updateItem!(mapInputToItem(item));
  };

  const handleDelete = (item: ProductListItemInput) => {
    props.deleteItem!(mapInputToItem(item));
  };

  return (
    <>
      <div className="list">
        <div className="list-item has-background-white-ter">
          <div
            className="has-text-right"
          >
            <div
              title="Grand Total"
              className="input is-static is-paddingless"
            >
              ${grandTotal}
            </div>
          </div>
        </div>
        {
          itemList.length > 0 &&
          <ProductListSortableContainer
            items={itemList}
            editingItemIds={props.editingItemIds || []}
            onChange={handleChange}
            onDelete={handleDelete}
            isSorting={isSorting}
            pressDelay={200}
            onSortStart={onSortStart}
            onSortEnd={onSortEnd}
            helperClass="sorting"
          />
        }
        {
          itemList.length < 1 &&
          (
            <div className="section has-text-centered">
              <div>Your list is empty.</div>
              <span>Add your first item </span>
              <i className="fas fa-arrow-down"></i>
            </div>
          )
        }
        <div
          className="list-item"
        >
          <button
            className="button is-small is-fullwidth"
            onClick={props.addItem}
          >
            <span className="icon">
              <i className="fas fa-plus"></i>
            </span>
            <span>Add Item</span>
          </button>
        </div>
      </div>
    </>
  );

};

export default ProductList;
